package br.ufrn.sigtcc.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import org.apache.commons.io.FilenameUtils;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

@ManagedBean(name="fileUploadController")
@RequestScoped
public class ControllerUpload {
	
	public ControllerUpload(){
		
	}
	private Logger logger = Logger.getLogger(ControllerUpload.class.getName()); 
	
	public void handleFileUpload(FileUploadEvent event){
		
		UploadedFile uploadedFile = event.getFile();
		String fileName = FilenameUtils.getName(uploadedFile.getFileName());
	   
	    byte[] conteudo = event.getFile().getContents();
	    
	    String caminho = "C://temp//" + event.getFile().getFileName();

		logger.log(Level.INFO, "Uploaded: {0}", fileName); 

		   	    try {

		    	       
		    	FileOutputStream out = new FileOutputStream(caminho);

		    	out.write(conteudo);
	            out.close();
	         
	            FacesContext.getCurrentInstance().addMessage(
			            null,
			            new FacesMessage(String.format(
			                    "Arquivo '%s' enviado com sucesso!",
			                    fileName)));

	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	}
}
